<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class admin_gallery extends CI_Controller {
    private $limit = 20;
    function __construct() {
        parent::__construct();
        $this->load->model('model_gallery', 'm_gall', TRUE);
        $this->load->model('model_event', 'm_event', TRUE);
    }
    
    function index() {
        if(!$this->session->userdata('admin_user')){
            redirect("admin_ippi","refresh");
        }
        if($this->session->userdata('admin_user')->level != 1){
            redirect("admin_home","refresh");
        }
        else{
            $data = array(
                'web_title' =>  'Admin Gallery',
                'main_view' =>  'mimin/gallery/index_new',
                'list_data' =>  $this->m_gall->get_all_gallery()
            );
        }
        
        $this->load->view('mimin/template/template_table',$data);
    }
    
    function images(){
        if(!$this->session->userdata('admin_user')){
            redirect("admin_ippi","refresh");
        }
        if($this->session->userdata('admin_user')->level != 1){
            redirect("admin_home","refresh");
        }
        else{
            $condition = " `type` = 'i'";
            $data = array(
                'web_title' =>  'Admin Gallery Image',
                'main_view' =>  'mimin/gallery/index_image',
                'list_data' =>  $this->m_gall->get_data_by_condition($condition)
            );
            $this->load->view('mimin/template/template_table',$data);
        }
    }

    function add_image(){
        if(!$this->session->userdata('admin_user')){
            redirect("admin_ippi","refresh");
        }
        if($this->session->userdata('admin_user')->level != 1){
            redirect("admin_home","refresh");
        }
        else{
            $data = array(
                'web_title'             =>  'New Gallery Data',
                'main_view'             =>  "mimin/gallery/add",
            );
            $this->load->view('mimin/template/template_upload',$data);
        }
    }
    
    function add_image_act() {
        $headers = apache_request_headers();
        $is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');
        if($is_ajax){
            if(!$this->session->userdata('admin_user')){
                die("Denied");
            }
            if($this->session->userdata('admin_user')->level != 1){
                die("Denied, has no Authentication");
            }
            $config['upload_path'] = './content/media/gallery/image/';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $config['max_size']	= '100';
            $this->load->library('upload');
            $this->upload->initialize($config);
            if (!$this->upload->do_upload()){
                echo    "<div class=\"alert alert-danger alert-dismissable\">"
                        . "<i class=\"fa fa-ban\"></i>"
                        . "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">x</button>"
                        . "<b>Alert!</b> "
                        . $this->upload->display_errors()
                        . "</div>";
            }
            else{
                date_default_timezone_set("Asia/Jakarta");
                $curdate = date("Y-m-d h:i:s");
                $upload_image = $this->upload->data();
                
                //create thumbnail
                $this->load->library('image_lib');
                $config['image_library']    = 'gd2';
                $config['source_image']     = 'content/media/gallery/image/'.$upload_image['file_name'];
                $config['create_thumb']     = TRUE;
                $config['maintain_ratio']   = TRUE;
                $config['width']            = 500;
                $config['height']           = 122;
                $config['new_image']        = 'content/media/gallery/image/thumb/'.$upload_image['file_name'];
                $config['thumb_marker']     = '';
                
                $this->image_lib->initialize($config); 
                $this->image_lib->resize();
                if (!$this->image_lib->resize()){
                    echo    "<div class=\"alert alert-danger alert-dismissable\">"
                        . "<i class=\"fa fa-ban\"></i>"
                        . "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">x</button>"
                        . "<b>Alert!</b> "
                        . $this->image_lib->display_errors()
                        . "</div>";
                    exit();
                }
                
                $isi = array(
                    'title'         =>  $this->input->post('title'),
                    'type'          =>  'i',    //i=image,v=video
                    'createdby'     =>  $this->session->userdata('admin_user')->id_admin,
                    'datecreated'   =>  $curdate,
                    'datemodified'  =>  $curdate,
                    'status'        =>  1,
                    'path'          =>  'content/media/gallery/image/'.$upload_image['file_name'],
                    'thumb'         =>  'content/media/gallery/image/thumb/'.$upload_image['file_name'].''
                );
                if($this->m_gall->save_data($isi)){
                    echo "<div class=\"alert alert-success alert-dismissable\">"
                        . "<i class=\"fa fa-check\"></i>"
                        . "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">x</button>"
                        . "<b>Alert!</b> "
                        . "New Slide image has been uploaded."
                        . "</div>";
                }
                else{
                    echo "<div class=\"alert alert-danger alert-dismissable\">"
                        . "<i class=\"fa fa-ban\"></i>"
                        . "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">x</button>"
                        . "<b>Alert!</b> "
                        . "Failed to upload image."
                        . "</div>";
                }
            }
        }
        else{
            die("Cannot access directly");
        }
    }
    
    /**
     * Show form upload video on gallery menu
     * 
     * @author  Dinov
     */
    function add_video(){
        if(!$this->session->userdata('admin_user')){
            redirect("admin_ippi","refresh");
        }
        if($this->session->userdata('admin_user')->level != 1){
            redirect("admin_home","refresh");
        }
        else{
            $data = array(
                'web_title'             =>  'New Gallery Data',
                'main_view'             =>  "mimin/gallery/add_video",
            );
            $this->load->view('mimin/template/template_upload',$data);
        }
    }
    
    function add_video_act(){
        $headers = apache_request_headers();
        $is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');
        if($is_ajax){
            if(!$this->session->userdata('admin_user')){
                die("Denied");
            }
            if($this->session->userdata('admin_user')->level != 1){
                die("Denied, has no Authentication");
            }
            $config['upload_path'] = './content/media/gallery/video/';
            $config['allowed_types'] = 'flv|mp4|3gp|avi';
            $config['max_size']	= '20000';
            
            
            $this->load->library('upload');
            $this->upload->initialize($config);
            
            
            
            if (!$this->upload->do_upload('userfile')){
                echo    "<div class=\"alert alert-danger alert-dismissable\">"
                        . "<i class=\"fa fa-ban\"></i>"
                        . "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">x</button>"
                        . "<b>Alert!</b> "
                        . $this->upload->display_errors()
                        . "</div>";exit();
            }
            $upload_video = $this->upload->data();
            $video_name = "";
            $video_name = $upload_video['file_name'];
            
            
            
            //upload thumbnail
            $config['upload_path'] = './content/media/gallery/video/thumb/';
            $config['allowed_types'] = 'jpeg|gif|jpg|png';
            $config['max_size']	= '100';
            $this->load->library('upload');
            $this->upload->initialize($config);
            
            
            
            if (!$this->upload->do_upload('thumbnail')){
                echo    "<div class=\"alert alert-danger alert-dismissable\">"
                        . "<i class=\"fa fa-ban\"></i>"
                        . "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">x</button>"
                        . "<b>Alert!</b> Thumbnail - "
                        . $this->upload->display_errors('','')
                        . "</div>";exit();
            }
            date_default_timezone_set("Asia/Jakarta");
            $curdate = date("Y-m-d h:i:s");
            $upload_image = $this->upload->data();



            $isi = array(
                'title'         =>  $this->input->post('title'),
                'type'          =>  'v',    //i=image,v=video
                'createdby'     =>  $this->session->userdata('admin_user')->id_admin,
                'datecreated'   =>  $curdate,
                'datemodified'  =>  $curdate,
                'status'        =>  1,
                'path'          =>  'content/media/gallery/video/'.$video_name,
                'thumb'         =>  'content/media/gallery/video/thumb/'.$upload_image['file_name'].''
            );
            if($this->m_gall->save_data($isi)){
                echo "<div class=\"alert alert-success alert-dismissable\">"
                    . "<i class=\"fa fa-check\"></i>"
                    . "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">x</button>"
                    . "<b>Alert!</b> "
                    . "New Video file has been uploaded."
                    . "</div>";
            }
            else{
                echo "<div class=\"alert alert-danger alert-dismissable\">"
                    . "<i class=\"fa fa-ban\"></i>"
                    . "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">x</button>"
                    . "<b>Alert!</b> "
                    . "Failed to upload Video."
                    . "</div>";
            }
        }
        else{
            die("Cannot access directly");
        }
    }
    
    function video(){
        if(!$this->session->userdata('admin_user')){
            redirect("admin_ippi","refresh");
        }
        if($this->session->userdata('admin_user')->level != 1){
            redirect("admin_home","refresh");
        }
        else{
            $condition = " `type` = 'v'";
            $data = array(
                'web_title' =>  'Admin Gallery Video',
                'main_view' =>  'mimin/gallery/index_video',
                'list_data' =>  $this->m_gall->get_data_by_condition($condition)
            );
            $this->load->view('mimin/template/template_table',$data);
        }
    }
    
    function detail($id=""){
        //SET TIME ZONE
        date_default_timezone_set("Asia/Jakarta");
        $curdate = date("Y-m-d h:i:s");
        if(!$this->session->userdata('admin_user')){
            redirect("admin_ippi","refresh");
        }
        elseif($id==""){
            redirect("admin_gallery","refresh");
        }
        else{
            $count_data = $this->m_gall->get_gallery_by_id($id,"count");
            if($count_data > 0){
                $data = $this->m_gall->get_gallery_by_id($id);
                $this->form_validation->set_rules('judul','Judul','required');
                if($this->form_validation->run() == FALSE){
                    $data = array(
                    'web_title'             =>  'Detail Gallery Data',
                    'main_view'             =>  "mimin/gallery/detail",
                    'list_data'             =>  $data,
                );
                $this->load->view("mimin/template/template_editor",$data);
                }
            }
            else{
                redirect("admin_gallery","refresh");
            }
        }
    }
    
    function detail_act(){
        $headers = apache_request_headers();
        $is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');
        if($is_ajax){
            if(!$this->session->userdata('admin_user')){
                $output = array(
                    'status'    => 0,
                    'msg'       => 'Need to relogin',
                );
                echo json_encode($output);exit();
            }
            if($this->session->userdata('admin_user')->level != 1){
                $output = array(
                    'status'    => 0,
                    'msg'       => 'Denied, has no Authentication',
                );
                echo json_encode($output);exit();
            }
            $this->form_validation->set_rules('id_gallery','ID Gallery','required');
            $this->form_validation->set_rules('title','Title','required');
            if($this->form_validation->run() == FALSE){
                $output = array(
                    'status'    => 0,
                    'msg'       => 'Missing fields Value',
                );
                echo json_encode($output);exit();
            }
            //SET TIME ZONE
            date_default_timezone_set("Asia/Jakarta");
            $curdate = date("Y-m-d h:i:s");
            $isi = array(
                'title'         =>  $this->input->post('title'),
                'datecreated'   =>  $curdate,
                'modifiedby'    =>  $this->session->userdata('admin_user')->id_admin,
            );
            if($this->m_gall->update_gallery($isi,$this->input->post('id_gallery'))){
                $output = array(
                    'status'    => 1,
                    'msg'       => 'Data has been updated',
                );
                echo json_encode($output);exit();
            }
            else{
                $output = array(
                    'status'    => 0,
                    'msg'       => 'failed update data',
                );
                echo json_encode($output);exit();
            }
        }
        else{
            die("Cannot access directly");
        }
    }
    
    function ajax_delete(){
        $headers = apache_request_headers();
        $is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');
        
        if($is_ajax){
            if(!$this->session->userdata('admin_user')){
                $output = array(
                    'status'    =>  0,
                    'msg'       =>  'You need to re-login',
                );
                echo json_encode($output);exit();
            }
            if($this->session->userdata('admin_user')->level != 1){
                $output = array(
                    'status'    =>  0,
                    'msg'       =>  'Denied, has no Authentication',
                );
                echo json_encode($output);exit();
            }
            $this->form_validation->set_rules('id_gallery','ID','required');
            if($this->form_validation->run() == FALSE){
                $output = array(
                    'status'    =>  0,
                    'msg'       =>  'Missing ID data',
                );
                echo json_encode($output);exit();
            }
            else{
                //get gallery
                $gallery    = $this->m_gall->get_gallery_by_id($this->input->post('id_gallery'), 'row');
                
                if( ippi_isset($gallery->id) > 0 ){
                    if($this->m_gall->delete($gallery->id)){
                        $success    = unlink(FCPATH . trim($gallery->path));
                        $success    = unlink(FCPATH . trim($gallery->thumb));
                        
                        $output = array(
                            'status'    =>  1,
                            'msg'       =>  'Successfully delete data, page will be refreshed in 3 seconds',
                        );
                        echo json_encode($output);exit();
                    }else{
                        $output = array(
                            'status'    =>  0,
                            'msg'       =>  'failed delete data',
                        );
                        echo json_encode($output);exit();
                    }
                }else{
                    $output = array(
                        'status'    =>  0,
                        'msg'       =>  'gallery data doesn\'t exist',
                    );
                    echo json_encode($output);exit();
                }
            }
        }
        else{
            die("Cannot access directly");
        }
    }
    
    public function do_upload_image() {
        if(!$this->session->userdata('admin_user')){
            die("Denied");
        }
        if($this->session->userdata('admin_user')->level != 1){
            die("Denied, has no Authentication");
        }
        
        // set the data for the json array
        $info                       = new StdClass;
        $error                      = '';
        $upload_path_url            = base_url() . 'content/media/gallery/image/';

        $config['upload_path']      = FCPATH . 'content/media/gallery/image/';
        $config['allowed_types']    = 'jpg|jpeg|png|gif';
        $config['max_size']         = '20480';

        $this->upload->initialize($config);
        
        $upload                     = $this->upload->do_upload();

        if (!$upload) {
            $error                  = strip_tags($this->upload->display_errors());
        } else {
            $data                   = $this->upload->data();
            
            // to re-size for thumbnail images un-comment and set path here and in json array
            $this->load->library('image_lib');

            $config['image_library']    = 'gd2';
            $config['source_image']     = 'content/media/gallery/image/'.$data['file_name'];
            $config['create_thumb']     = TRUE;
            $config['maintain_ratio']   = FALSE;
            $config['width']            = 150;
            $config['height']           = 100;
            $config['new_image']        = 'content/media/gallery/image/thumb/'.$data['file_name'];
            $config['thumb_marker']     = '';
            
            $this->image_lib->initialize($config); 
            $this->image_lib->resize();
            
            // save to database
            $curdate    = date("Y-m-d h:i:s");
            $title      = ippi_isset($this->input->post('title'));
            $date       = ippi_isset($this->input->post('date'));
            $date       = ( !empty($date) ? $date : $curdate );
            $isi        = array(
                'title'         =>  ( !empty( $title ) ? $title : $data['raw_name'] ),
                'type'          =>  'i',
                'createdby'     =>  $this->session->userdata('admin_user')->id_admin,
                'date'          =>  $date,
                'datecreated'   =>  $curdate,
                'datemodified'  =>  $curdate,
                'status'        =>  1,
                'path'          =>  'content/media/gallery/image/'.$data['file_name'],
                'thumb'         =>  'content/media/gallery/image/thumb/'.$data['file_name'].''
            );

            if( $this->m_gall->save_data($isi) ){
                $insert_id      = $this->db->insert_id();
            }else{
                $error          = strip_tags($this->upload->display_errors());
            }
            
            $info->name         = $data['file_name'];
            $info->date         = $date;
            $info->size         = $data['file_size'] * 1024;
            $info->type         = $data['file_type'];
            $info->url          = $upload_path_url . $data['file_name'];
            
            $info->thumbnailUrl = $upload_path_url . 'thumb/' . $data['file_name'];
            $info->deleteUrl    = 'admin_gallery/delete_image/' . ( $insert_id ? $insert_id : 0 );
            $info->deleteType   = 'DELETE';            
        }

        $info->error        = $error;
        $files[]            = $info;
        
        //this is why we put this in the constants to pass only json data
        if (IS_AJAX) {
            echo json_encode(array("files" => $files));
            //this has to be the only data returned or you will get an error.
            //if you don't give this a json array it will give you a Empty file upload result error
            //it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
            //so that this will still work if javascript is not enabled
        }
    }
    
    public function delete_image($id) {
        $success        = false;
        
        if( !$id ){
            $success    = false;
        }else{
            //get gallery
            $gallery    = $this->m_gall->get_gallery_by_id($id, 'row');
            
            if( ippi_isset($gallery->id) > 0 ){
                if($this->m_gall->delete($id)){
                    //gets the job done but you might want to add error checking and security
                    $success    = unlink(FCPATH . trim($gallery->path));
                    $success    = unlink(FCPATH . trim($gallery->thumb));
                }
            }
        }

        //info to see if it is doing what it is supposed to
        $info           = new StdClass;
        $info->sucess   = $success;
        $info->path     = base_url() . trim($gallery->path);
        $info->file     = is_file(FCPATH . trim($gallery->path));
        
        if (IS_AJAX) {
            //I don't think it matters if this is set but good for error checking in the console/firebug
            echo json_encode(array($info));
        } else {
            //here you will need to decide what you want to show for a successful delete        
            $file_data['delete_data'] = $file;
            $this->load->view('admin/delete_success', $file_data);
        }
    }
    
    /**
	 * Load Image Data function.
     * 
     * @param[in] int $offset Offset of Table Gallery data
     * 
     * @return AJAX String
	 */
    function image_data($offset=0){
        // Set variables
        $limit          = get_option('news_limit');
       
        // Get images data
        $images_data    = $this->m_gall->get_all_images_data();
        $image          = '';
        
        // Check response of get news data
        if( !empty($images_data) ){
            $total      = ippi_get_last_found_rows();
            
            foreach($images_data as $r){                
                $image .= '
                <div class="col-lg-2 col-md-4 col-xs-6 image-choose">
                    <a href="#" class="image_event">
                        <div class="check">
                            <label><input name="image_event[]" type="checkbox" class="minimal-red image_event_cb" value="' . $r->id . '" /></label>
                        </div>
                        <img src="'.( !empty($r->thumb) && file_exists($r->thumb) ? site_url($r->thumb) : site_url('content/media/gallery/video/thumb/novideo.jpg') ) . '" />
                    </a>
                </div>';
            }
        }
        
        // Set JSON data
        $data = array('image' => $image);
        
        // JSON encode data
        die(json_encode($data));
    }
}

/* End of file admin_event.php */
/* Location: ./application/controllers/admin_event.php */